﻿using System.ServiceModel;

namespace Macds.Core.Remoting
{
    public class RemoteChannelManager<T>
    {
        private ChannelFactory<T> channel;
        private T service;
        private string uri;
        private string domainName;
        private BindingType bindingType;

        public RemoteChannelManager(string uri, string domainName, BindingType bindingType)
        {
            Initialize(uri, domainName, bindingType);
        }

        public RemoteChannelManager(string uri, string domainName)
        {
            Initialize(uri, domainName, BindingType.Tcp);
        }

        /// <summary>
        /// Service instance created
        /// </summary>
        public T Service
        {
            get
            {
                return service;
            }
        }

        /// <summary>
        /// Call always this method to close the current service connection
        /// </summary>
        public void Close()
        {
            if (channel != null)
            {
                channel.Close();
                service = default(T);
                channel = null;
            }
        }

        protected void Initialize(string uri, string domain, BindingType type)
        {
            this.bindingType = type;
            this.domainName = domain;
            this.uri = uri;

            GetService();
        }

        protected void GetService()
        {
            if (service != null && service.GetType() == typeof(T) && channel != null && channel.State == CommunicationState.Opened)
                return;

            if (channel != null)
                if (channel.State == CommunicationState.Opened)
                    Close();

            channel = new ChannelFactory<T>();
            service = new RemoteFactory(BindingType.Tcp).CreateInstance<T>(channel, this.uri, this.domainName);
        }
    }
}
